import { login, logout, getInfo } from '@/api/user'
//对浏览器的cookie操作
import { getToken, setToken, removeToken } from '@/utils/auth'
//重置路由
import { resetRouter } from '@/router/index.js'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    accountType: undefined
  }
}

//私有的变量vuex
const state = getDefaultState()

//setter方法 vuex
const mutations = {
  RESET_STATE: (state) => {
    //浅拷贝对象
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_AccountType: (state, value) => {
    state.accountType = value
  }
}

//动作 vuex
const actions = {
  // user login
  login({ commit }, userInfo) {
    const formData={
      username: userInfo.loginName.trim(),
      password: userInfo.loginPwd.trim(),
      uuid: userInfo.uuid.trim(),
      code: userInfo.code.trim()
    }
    // 异步编程模型
    return new Promise((resolve, reject) => {
      //调用后台的 axios请求
      login(formData).then(response => {
        const { data } = response
        //为vuex的user模块设定令牌, vuex不能进行页面刷新
        commit('SET_TOKEN', data)
        //把令牌存入到 浏览器 cookie中
        setToken(data)
        //调用外部的方法
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          return reject('获取用户信息失败，请重新登陆.')
        }

        const { name, avatar, accountType } = data
         
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_AccountType', accountType)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        //删除浏览器中的cookie的令牌
        removeToken() 
        //重置路由
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

